﻿using System;
using System.Threading.Tasks;
using CAPDemo.Events;
using CAPDemo.UserService.Dtos;
using CAPDemo.UserService.Models;
using DotNetCore.CAP;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace CAPDemo.UserService.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class UserController : ControllerBase
    { 
        private readonly ILogger<UserController> _logger;
        private readonly ICapPublisher _capPublisher;
        private readonly UserDbContext _dbContext;

        public UserController(ILogger<UserController> logger, ICapPublisher capPublisher, UserDbContext dbContext)
        {
            _logger = logger;
            _capPublisher = capPublisher;
            _dbContext = dbContext;
        }

        [HttpGet]
        public IActionResult Get()
        {
            var random = new Random();

            return new JsonResult(random.Next());
        }

        [HttpPatch]
        public async Task PatchAsync(UpdateUserDto input)
        {
            using (var transaction = _dbContext.Database.BeginTransaction())
            {
                var userInfo = await _dbContext.UserInfos.FirstAsync(u => u.Id == input.Id);
                userInfo.Address = input.Address;
                await _dbContext.SaveChangesAsync();

                await _capPublisher.PublishAsync(nameof(UserAddressUpdatedEvent), new UserAddressUpdatedEvent(input.Id, input.Address));

                transaction.Commit();
            }
        }
    }
}
